﻿using DotNetty.Transport.Channels;
using System.Net;

namespace FirstDemoServer
{
    /// <summary>
    /// 服务端自定义处理器
    /// </summary>
    public class DemoServerHandler : SimpleChannelInboundHandler<string> // SimpleChannelInboundHandler这里泛型指定接收的类型为String
    {
        /// <summary>
        /// 接收到客户端数据时触发
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="msg"></param>
        /// <exception cref="NotImplementedException"></exception>
        protected override void ChannelRead0(IChannelHandlerContext ctx, string msg)
        {
            Console.WriteLine("来自客户端的消息:" + msg + "\r\n");
        }

        /// <summary>
        /// 在客户端连接时触发
        /// </summary>
        /// <param name="context"></param>
        public override void ChannelActive(IChannelHandlerContext context)
        {
            // 发送的数据先写入缓冲区,你可以多调用几次,最后使用context.Flush()清空缓冲区
            // context.WriteAsync();
            // context.WriteAsync();
            // context.WriteAsync();
            // context.Flush();

            Console.WriteLine("ChannelActive");
            // 发送并立即清空缓冲区(相当于上面代码的合体)
            context.WriteAndFlushAsync(string.Format("welcome to {0}!\r\n", Dns.GetHostName()));
            context.WriteAndFlushAsync(string.Format("it is {0}!\r\n", DateTime.Now));
        }

        /// <summary>
        /// 服务端读取完客户端发送过来的数据之后触发
        /// </summary>
        /// <param name="context"></param>
        public override void ChannelReadComplete(IChannelHandlerContext context)
        {
            Console.WriteLine("ChannelReadComplete");
        }

        /// <summary>
        /// 客户端已注册时触发
        /// </summary>
        /// <param name="context"></param>
        public override void ChannelRegistered(IChannelHandlerContext context)
        {
            Console.WriteLine("ChannelRegistered");
        }

        /// <summary>
        /// 客户端已注销时触发
        /// </summary>
        /// <param name="context"></param>
        public override void ChannelUnregistered(IChannelHandlerContext context)
        {
            Console.WriteLine("ChannelUnregistered");
        }

        /// <summary>
        /// 客户端与服务器断开连接时触发
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task DisconnectAsync(IChannelHandlerContext context)
        {
            Console.WriteLine("DisconnectAsync");
            return base.DisconnectAsync(context);
        }

        /// <summary>
        /// 客户端关闭时触发
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task CloseAsync(IChannelHandlerContext context)
        {
            Console.WriteLine("CloseAsync");
            return base.CloseAsync(context);
        }
    }
}